package api

import (
	"errors"
	"fmt"
	"github.com/labstack/echo/v4"
	"longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/const"
	string2 "longmen/server/pkg/common/helper/string"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/redis/cache"
	"net/http"
	"net/url"
)

// @Summary 发起支付下单请求
// @Description 发起支付下单请求
// @Accept  json
// @Produce  json
// @Tags Charge
// @Param   sendBody body api_models.OrderReq true "body"
// @Success 200 {object} api_models.OrderResp "result"
// @Router /api/charge/commitOrder [POST]
func (base *Controller) CommitOrder(c echo.Context) error {
	r := &api_models.OrderReq{}
	if err := util.Json2Struct(c.Get("body").(string), r); err != nil {
		return util.BadParam(c, err)
	}
	cfgPri := cache.GetConfigPri()
	if cfgPri.PayNotifyDomain == "" {
		return util.BuildFail(c, 1, "支付回调域名未配置", errors.New("支付回调域名未配置"))
	}
	resp, err := base.Service.CommitOrder(r, cfgPri.PayNotifyDomain, c.Get("uid").(int))
	if err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	return util.BuildSuccess(c, resp, "")
}

// 服务器异步通知（notify_url）
func (base *Controller) OrderResultNotify(c echo.Context) error {
	// 不知道为什么c.bind()无法解析form数据
	u, err := url.Parse("http://path/?" + c.Get("body").(string))
	if err != nil {
		return util.BadParam(c, err)
	}
	query := u.Query()
	r := &api_models.OrderResultNotifyReq{
		Memberid:      query.Get("memberid"),
		Orderid:       query.Get("orderid"),
		TransactionId: query.Get("transaction_id"),
		Amount:        query.Get("amount"),
		Datetime:      query.Get("datetime"),
		Returncode:    query.Get("returncode"),
		Sign:          query.Get("sign"),
	}
	if len(query.Get("attach")) > 0 {
		r.Attach = query.Get("attach")
	}
	global.Log.Debugf("OrderResultNotify: %s, param: %+v", fmt.Sprintf("Method: %s, URL: %s",
		c.Request().Method,
		c.Request().URL.String(),
	), r)
	if err := _const.Validate.Struct(r); err != nil {
		return util.BadParam(c, err)
	}
	// 接收到服务器点对点通讯时，在页面输出“OK”（ 没有双引号，OK 两个字母大写 )
	// 请注意!务必要在页面输出两个大写的OK, 否则会重复5次发送点对点通知
	html, err := base.Service.OrderResultNotify(r)
	if err != nil {
		global.Log.Debugf("OrderResultNotify failed: %v", err)
	}
	return c.HTML(http.StatusOK, html)
}

// @Summary 查找订单
// @Description 查找订单
// @Accept  json
// @Produce  json
// @Tags Charge
// @Param   sendBody body api_models.SearchOrderReq true "body"
// @Success 200 {object} api_models.SearchOrderResp "result"
// @Router /api/charge/searchOrder [POST]
func (base *Controller) SearchOrder(c echo.Context) error {
	r := &api_models.SearchOrderReq{}
	if err := util.Json2Struct(c.Get("body").(string), r); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(r); err != nil {
		return util.BadParam(c, err)
	}
	resp, err := base.Service.QueryOrder(r)
	if err != nil {
		return util.BadParam(c, err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary 订单列表
// @Description 查找订单
// @Accept  json
// @Produce  json
// @Tags Charge
// @Param   sendBody body api_models.PageParam true "body"
// @Success 200 {object} api_models.OrderListResp "result"
// @Router /api/charge/orderList [POST]
func (base *Controller) OrderList(c echo.Context) error {
	r := &api_models.PageParam{}
	if err := util.Json2Struct(c.Get("body").(string), r); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(r); err != nil {
		return util.BadParam(c, err)
	}
	r.Page = string2.GetDefaultNum(r.Page, 1)
	r.Size = string2.GetDefaultNum(r.Size, 20)
	resp, err := base.Service.OrderList(c.Get("uid").(int), r)
	if err != nil {
		return util.BadParam(c, err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary 克拉充值数量推荐列表
// @Description 克拉充值数量推荐列表
// @Accept  json
// @Produce  json
// @Tags Charge
// @Success 200 {object} models_main.GoldPrice "result"
// @Router /api/charge/chargePriceList [POST]
func (base *Controller) GetPriceList(c echo.Context) error {
	list, err := base.Service.GetPriceList()
	if err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	return util.BuildSuccess(c, list, "")
}

// calBackHtml 支付成功跳转页面地址
func (base *Controller) CalBackHtml(c echo.Context) error {
	c.HTML(200, "ok")
	return nil
}
